<?php

namespace App\Http\Middleware;

use App\Models\CompetiteActivityGroup;
use App\Models\Manage;
use App\Models\UserInfo;
use Closure;
use Illuminate\Http\Request;

/**
 * 验证前台用户绑定token 或 团队账号token  (token 可选的情况)
 */
class CheckMayWebAndGroupToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        //  $request->user_info = ['id'=>1,'account_id'=>1];
        //  $request->manage_id = 1;
        //  return $next($request);

        $token = $this->getToken($request);
        $group_token = $this->getGroupToken($request);

        if (empty($token) && empty($group_token)) {
            $request->user_info = ['id' => '', 'account_id' => '', 'wechat_id' => '', 'group_id' => ''];
            return $next($request);
        }

        $user_info = [];
        //验证token有效期
        if ($token) {
            $user_info = UserInfo::select('id', 'account_id', 'wechat_id')->where('token', $token)->first();
        }
        if (empty($user_info) || !empty($group_token)) {
            //获取团队账号是否过期
            if ($group_token) {
                $group_info = CompetiteActivityGroup::where('token', $group_token)->where('is_del', 1)->first();
                if (empty($group_info)) {
                    return  response()->json(['code' => 206, 'msg' => 'token无效']);
                }
            } else {
                return  response()->json(['code' => 206, 'msg' => 'token无效']);
            }
        }

        if ($user_info) {
            $user_info = $user_info->toArray();
        } else {
            $user_info['id'] = null;
            $user_info['account_id'] = null;
            $user_info['wechat_id'] = null;
        }
        //增加团队账号
        if (!empty($group_info['id'])) {
            $user_info['group_id'] = $group_info['id'];
            $user_info['group_con_id'] = $group_info['con_id'];
        } else {
            $user_info['group_id'] = null;
            $user_info['group_con_id'] = null;
        }
        $request->user_info = $user_info;
        return $next($request);
    }

    /**
     * 获取请求参数中的 token 
     * @param request  object 请求参数对象
     */
    public function getToken($request)
    {
        $token = $request->token;
        return $token;
    }

    /**
     * 获取请求参数中的 group_token 
     * @param request  object 请求参数对象
     */
    public function getGroupToken($request)
    {
        $group_token = $request->group_token;
        $group_token_con_id = $request->con_id;
        if (empty($group_token) || empty($group_token_con_id)) {
            return []; //团队token与大赛id 必须同时存在
        }
        return ['group_token' => $group_token, 'group_token_con_id' => $group_token_con_id];
    }
}
